package com.abs.orm.db.jdbc;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class TransactionImpl implements Transaction {
	private static Transaction transaction;
	private final static Map<Thread, Connection> connectionMap = new HashMap<Thread, Connection>();

	private TransactionImpl() {
		super();
	}

	public static Transaction getInstance() {
		if (null == transaction) {
			transaction = new TransactionImpl();
		}
		return transaction;
	}

	@Override
	public void begin() {
		Connection connection = connectionMap.get(Thread.currentThread());
		if (null == connection) {
			connection = ConnectionManager.getConnection();
			try {
				connection.setAutoCommit(false);
				connectionMap.put(Thread.currentThread(), connection);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			try {
				connection.setAutoCommit(false);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@Override
	public void commit() {
		Connection connection = connectionMap.get(Thread.currentThread());
		if (null != connection) {
			try {
				connection.commit();
				connection.setAutoCommit(true);
				connectionMap.remove(connection);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@Override
	public void rollback() {
		Connection connection = connectionMap.get(Thread.currentThread());
		if (null != connection) {
			try {
				connection.rollback();
				connection.setAutoCommit(true);
				connectionMap.remove(connection);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
